const API = require('../../../utils/api')
// pages/sign/codeSign.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    signDataId:'',
    signDisabled:false,
    signDetails:null,
    signFlag:false //可以签到表示位
  },
  /**
   * 生命周期函数--监听页面加载
   */
 async onLoad(options) {
    const id = options.id;
    this.setData({
      signDataId: id
    });
    let signRes = await this.getSignResult(id);
    //说明还未签到 
    if(signRes==null){
      await this.codeSign()
      await this.getSignResult(id);
    }else{
      this.setData({
        signDetails:signRes,
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    //清除延时任务
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  },
async codeSign(){
   this.setData({
    signDisabled:true
   })
  await API.signIn(this.data.signDataId).then(res=>{
    wx.showToast({
      title: '扫码签到成功',
      icon: 'success'
    });
    this.setData({
      signFlag:false
     })
  }).catch(error=>{
    this.setData({
      signFlag:true
     })
    wx.showToast({
      title: error.message ,
      icon: 'error'
    });
  }).finally(()=>{
    this.setData({
      signDisabled:false
     })
  })
  },
  backHome(){
    wx.navigateBack()
  },
  async getSignResult(id){
    let signRes = await API.signResult(id)
    if(signRes == null){
      this.setData({
        signDetails:null,
        signFlag:true
      })
    }else{
      this.setData({
        signDetails:signRes,
        signFlag:false
      })
    }
    return signRes
  }
})

// this.timer = setTimeout(()=>{
//   wx.navigateBack()
// },2000)